package com.lzy.system.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.conf.RedisUtil;
import com.lzy.exception.BusException;
import com.lzy.system.organization.entity.SysLoginLog;
import com.lzy.system.organization.mapper.SysLoginLogMapper;
import com.lzy.system.organization.service.ISysLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 登录日志 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2023-11-14
 */
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements ISysLoginLogService {

    @Autowired
    RedisUtil redisUtil;
    @Value("${jwt.expire}")
    private int expire;
    @Override
    public boolean add(SysLoginLog sysLoginLog) throws BusException {
        boolean save = this.save(sysLoginLog);
        if(save){
            //个redis插入一个token缓存
            redisUtil.setCacheObject("token-"+sysLoginLog.getToken_uuid(), sysLoginLog,expire, TimeUnit.MINUTES);
        }
        return save;
    }

    @Override
    public IPage<SysLoginLog> getList(String userId,String userName,int limit, int page) throws BusException {
        Page<SysLoginLog> Ipage = new Page<>(page,limit);
        QueryWrapper<SysLoginLog> queryWrapper = new QueryWrapper();
        if(!StrUtil.isBlank(userId)){
            queryWrapper.like("userId",userId);
            queryWrapper.or();
        }
        if(!StrUtil.isBlank(userName)){
            queryWrapper.like("userName",userName);
            queryWrapper.or();
        }
        queryWrapper.orderByDesc("login_time");
        IPage res = this.page(Ipage, queryWrapper);
        return res;
    }
}
